package 每日一题;

public class 有效的井字游戏 {
    //1、X必须比O多1个或者相同，否则false；
    // 2、X赢的时候必须比O多1个，否则false； 3、O赢得时候个数与X相同，否则false；
    public boolean validTicTacToe(String[] board) {
        int xCount=0,oCount=0;
        for (String s : board) {
            for (char c : s.toCharArray()) {
                xCount+=(c=='X'?1:0);
                oCount+=(c=='O'?1:0);
            }
        }
        System.out.println(xCount+" "+oCount);
        //两个都不满足返回false，否则返回True
        if (xCount!=oCount && xCount-oCount!=1)
            return false;
        if (isWin(board,'X') && xCount-oCount!=1)
            return false;
        if (isWin(board,'O') && xCount!=oCount)
            return false;
        return true;
    }
    boolean isWin(String[] board,char p){
        for (int i = 0; i < 3; i++) {
            //列相等
            if (p == board[0].charAt(i) && p == board[1].charAt(i) && p == board[2].charAt(i)) {
                return true;
            }
            //行相等
            if (p == board[i].charAt(0) && p == board[i].charAt(1) && p == board[i].charAt(2)) {
                return true;
            }
        }
        //对角线相等
        if (p == board[0].charAt(0) && p == board[1].charAt(1) && p == board[2].charAt(2)) {
                return true;
        }
        if (p == board[0].charAt(2) && p == board[1].charAt(1) && p == board[2].charAt(0)) {
                return true;
        }
        return false;
    }
}

